package com.thread.DeadLock;
/*死锁：多个线程互相抱者对方的资源，然后形成僵持
死锁的解决方案：一次只拿一个资源，避免一次拿多个资源
 */

public class DeadLock {
    public static void main(String[] args) {
        Eat son = new Eat(0,"儿子");
        Eat daughter = new Eat(1,"女儿");
        son.start();
        daughter.start();

    }
}

//面包类
class Bread{

}

//果酱类
class Jam{

}

//吃面包沾酱
class Eat extends Thread {
    //需要的资源只有一份，用static修饰
    static Bread bread = new Bread();
    static Jam jam = new Jam();
    int choice;//选择
    String baby;//想吃面包沾酱的人

    //构造器
    public Eat(int choice, String baby) {
        this.choice = choice;
        this.baby = baby;
    }

    //重写run方法
    @Override
    public void run() {
        //吃面包沾酱
        try {
            eat();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    //互相持有对方的资源——>锁，就需要拿到对方的资源
    private void eat() throws InterruptedException {
        if (choice == 0) {
            synchronized (bread) {//获得面包的锁
                System.out.println(this.baby + "拿到面包的锁");

                Thread.sleep(1000);//一秒钟后想去拿果酱的锁
                synchronized (jam) {
                    System.out.println(this.baby + "拿到果酱的锁");
                }
            }
        } else {
            synchronized (jam) {//获得果酱的锁
                System.out.println(this.baby + "拿到面包的锁");
                Thread.sleep(2000);//一秒钟后想去拿面包的锁
                synchronized (bread) {
                    System.out.println(this.baby + "拿到果酱的锁");
                }
                //线程获取资源，一次拿一个，就能避免死锁
//                synchronized (bread) {
//                    System.out.println(this.baby + "拿到果酱的锁");
            }
        }
    }
}